package com.web.task;

import com.alipay.api.response.AlipayTradeQueryResponse;
import com.web.config.PayConfiguration;
import com.web.dao.*;
import com.web.entity.*;
import com.web.manager.CoreManager;
import com.web.manager.jpush.SendJPushMessage;
import com.web.pay.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import static java.math.BigDecimal.ROUND_HALF_DOWN;

/**
 *
 * @author FDjavaone
 * @date 2017/9/15
 */
@Component
@Configurable
@EnableScheduling
@Slf4j
public class FixOrderStatusJob {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private PlatformMapper platformMapper;
    @Autowired
    private ProfitConfigMapper profitConfigMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private PoundageConfigMapper poundageConfigMapper;
    @Autowired
    private  RegionRecordMapper regionRecordMapper;
    @Autowired
    private PayConfiguration payConfiguration;
    @Autowired
    private CoreManager coreManager;

    @Scheduled(cron = "0 */5 * * * ?")
    public void queryOrderPayStatus()  {

        List<Order> waitConfirmPayStatus = orderMapper.selectByStatus();
        log.info("未确认支付结果的订单数：" + waitConfirmPayStatus.size());
        for (Order o : waitConfirmPayStatus) {
            try {
                //支付宝支付订单查询
                AliPayDto aliPayDto = new AliPayDto();
                aliPayDto.setPayAppid(payConfiguration.getAli().getAppid());
                aliPayDto.setPayUrl(payConfiguration.getAli().getUrl());
                aliPayDto.setPaySelfSecret(payConfiguration.getAli().getSelfSecret());
                aliPayDto.setPayPublicSecret(payConfiguration.getAli().getPublicSecret());
                aliPayDto.setPayPublicSecret2(payConfiguration.getAli().getPublicSecret2());
                aliPayDto.setOutTradeNo(o.getOrderNum());
                AlipayTradeQueryResponse aliResponse = AliPayManage.mg.tradeQuery(aliPayDto);
                boolean payFlag = false;
                boolean isAli=false;
                if (aliResponse.getSubCode()==null) {
                    //判断交易状态
                    if("TRADE_SUCCESS".equals(aliResponse.getTradeStatus())){
                        //交易成功
                        log.info("订单：" + o.getOrderNum() + "支付成功");
                        payFlag = true;
                        isAli=true;
                    }
                } else if ("ACQ.TRADE_HAS_SUCCESS".equals(aliResponse.getSubCode())) {
                    //交易成功
                    log.info("订单：" + o.getOrderNum() + "支付成功");
                    payFlag = true;
                    isAli=true;
                } else if ("ACQ.TRADE_NOT_EXIST".equals(aliResponse.getSubCode())) {
                    //交易不存在或者为微信交易订单，再查询微信的用户
                    WxPayDto wxPayDto = new WxPayDto();
                    wxPayDto.setAppid(payConfiguration.getWx().getAppId());
                    wxPayDto.setMch_id(payConfiguration.getWx().getMchId());
                    wxPayDto.setSignKey(payConfiguration.getWx().getSignKey());
                    wxPayDto.setOut_trade_no(o.getOrderNum());
                    PayResponse response = WxPayManage.mg.orderquery(wxPayDto);
                    JSONObject json = JSONObject.fromObject(response.getParams());

                    if ("SUCCESS".equals(json.get("trade_state"))) {
                        //微信支付成功
                        log.info("订单：" + o.getOrderNum() + "微信支付成功");
                        payFlag = true;
                    } else {
                        //微信支付宝都未支付

                    }
                }
                Date date = new Date();
                if (payFlag) {
                    //支付成功
                    String orderNum = o.getOrderNum();
                    //消费者信息
                    Member member = memberMapper.selectByPrimaryKey(o.getmId());
                    BigDecimal totalPrice = o.getTotalPrice().add(o.getTipPrice());

                    CompanyReport companyReport=new CompanyReport();
                    if(isAli){
                        companyReport.setReserve1("支付宝消费");
                        companyReport.setReserve2("5");
                    }else {
                        companyReport.setReserve1("微信消费");
                        companyReport.setReserve2("4");
                    }

                    if(o.getOrderType().equals("online")){
                        //企业订单
                        //更新订单支付状态
                        Order update = new Order();
                        update.setStatus(1);
                        update.setId(o.getId());
                        orderMapper.updateByPrimaryKeySelective(update);

                    }else{


                        //消费者账户信息
                        Account account = accountMapper.selectByMid(o.getmId());

                        //商家店铺信息
                        Store store = storeMapper.selectByPrimaryKey(o.getStoreId());
                        //商家账户信息
                        Account merchantAccount = accountMapper.selectByMid(store.getmId());
                        //商户信息
                        Member merchant = memberMapper.selectByPrimaryKey(store.getmId());

                        Member memberUp = null;
                        if (member.getInvitedCode() != null) {
                            //用户上线
                            memberUp = memberMapper.selectMyUp(member.getInvitedCode());
                        }

                        Member merchantUp = null;
                        if (merchant.getInvitedCode() != null) {
                            //商户上线
                            merchantUp = memberMapper.selectMyUp(merchant.getInvitedCode());
                        }

                        //店铺的省市区三级代理商获取
                        RegionRecord province = regionRecordMapper.selectProvince(store.getProvince());
                        RegionRecord city = regionRecordMapper.selectProvinceAndCity(store.getProvince(), store.getCity());
                        RegionRecord region = regionRecordMapper.selectProvinceAndCityAndRegion(store.getProvince(), store.getCity(), store.getRegion());

                        //总的奖励分配
                        BigDecimal totalBonus = new BigDecimal(0);

                        //利润分配配置
                        ProfitConfig config = profitConfigMapper.selectByPrimaryKey(1L);
                        //msk卖出配置
                        PoundageConfig poundageConfig = poundageConfigMapper.selectByPrimaryKey(1L);
                        //平台账户信息
                        Platform platform = platformMapper.selectByPrimaryKey(1L);

                        synchronized (this) {

                            //核心处理方法
                            coreManager.coreOperation(o,totalPrice,totalBonus,o.getTransferPrice(),config,poundageConfig,platform,member,memberUp,account,merchant,merchantUp
                                    ,merchantAccount,province,city,region,date,store,companyReport);

                        }
                    }



                    //boolean flag=iUserOrderService.updateOrder(orderId);
                    //log.info("订单修改状态："+(flag?"成功":"失败"));
                    // 推送消息
                    Message message = new Message();
                    message.setModifyTime(date);
                    message.setCreateTime(date);
                    message.setContent("尊敬的用户您使用支付宝或支付宝支付订单：" + orderNum + "，" + totalPrice + " 元。成功支付！");
                    message.setTitle("支付结果");
                    message.setFrom(0L);
                    message.setFromName("系统");
                    message.setTarget(member.getId());
                    message.setTargetName(member.getNickName());
                    messageMapper.insertSelective(message);
                    SendJPushMessage.jPushByMessage(message);


                } else {
                    //支付失败或订单未创建
                    //支付不成功回退订单锁定库存，删除订单，及订单明细
                    List<OrderGoods> orderGoods = orderGoodsMapper.selectByOrderId(o.getId());
                    for (OrderGoods og : orderGoods) {
                        //回退库存
                        goodsMapper.numAdd(og.getNum(), o.getId());
                    }

                    orderMapper.deleteByPrimaryKeyLogic(o.getOrderNum());
                    Message message = new Message();
                    message.setModifyTime(date);
                    message.setCreateTime(date);
                    message.setContent("尊敬的用户您支付订单：" + o.getOrderNum() + "，" + o.getTotalPrice().add(o.getTipPrice()) + " 元。支付失败！");
                    message.setTitle("支付结果");
                    message.setFrom(0L);
                    message.setFromName("系统");
                    message.setTarget(o.getmId());
                    message.setTargetName("");
                    messageMapper.insertSelective(message);
                    SendJPushMessage.jPushByMessage(message);


                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }



}
